<template>
  <div>
    <el-dialog class="assign-role" title="分配角色" :visible="showRoleDialog" @close="closeDialog" @open="dialogOpen">
      <!-- 这里准备复选框 -->
      <template>
        <el-checkbox-group v-model="roleIds" v-loading="loading">
          <!-- 表格的渲染遍历 只需要添加prop -->
          <el-checkbox v-for="item in list" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>

        </el-checkbox-group>
      </template>
      <template #footer>
        <el-button type="primary" size="small" @click="clickSubmit">确认</el-button>
        <el-button size="small" @click="closeDialog()">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { reqAssignRoles, reqGetRoleList } from '@/api/setting'
import { reqGetUserDetailById } from '@/api/user'
export default {
  name: 'AssignRole',
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    userId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      roleIds: [], // 选中的角色
      list: [], // 全部的角色
      loading: false

    }
  },
  methods: {
    // 关闭弹出层
    closeDialog() {
      this.$emit('update:showRoleDialog', false)
    },
    // 发请求-拿到全部角色
    async getRoleList() {
      const { data: { rows }} = await reqGetRoleList(1, 999)
      console.log('我是拿到的所有角色', rows)
      this.list = rows
    },
    // 发请求-拿到用户当前的角色，进行回显
    async getUserDetailById() {
      const { data: { roleIds }} = await reqGetUserDetailById(this.userId)
      console.log(roleIds, '我是当前的角色信息')
      this.roleIds = roleIds
    },

    // 弹出层显示的时候触发事件处理
    dialogOpen() {
    //  可以用一个promise.all方法来进行关闭loading 加载的效果
      this.loading = 'true'
      Promise.all([this.getRoleList(), this.getUserDetailById()]).then(() => {
        this.loading = false
      }).catch((error) => {
        console.log(error)
      })
    },
    // 点击确定-提示用户修改成功-发起请求-重新渲染-关闭弹层
    async clickSubmit() {
      // 发起请求-里面发送的数据一个是用户id一个是roleIds
      await reqAssignRoles({
        id: this.userId,
        roleIds: this.roleIds
      })
      // 给用户一个提示
      this.$message.success('修改角色成功')
      // 关闭弹层
      this.closeDialog()
    }
  }
}
</script>

<style lang="scss" scoped>
.assign-role {
  ::v-deep {
    .el-checkbox {
      font-size: 30px;
    }
  }
}
</style>
